<?php
/**
 *  MyApp_MailSender.php
 *
 */

/**
 *
 *  @access     public
 *  @package    Ethna
 */
class MyApp_MailSender extends Ethna_MailSender
{
    function send($to, $template, $macro, $attach = null)
    {
        if ($template === MAILSENDER_TYPE_DIRECT) {
            $mail = $macro;
        } else {
            $renderer =& $this->getTemplateEngine();

            $renderer->setProp("env_datetime", strftime('%Y年%m月%d日 %H時%M分%S秒'));

            if (!empty($_SERVER["HTTP_USER_AGENT"])) {
                $renderer->setProp("env_useragent", $_SERVER["HTTP_USER_AGENT"]);
            }
            if (!empty($_SERVER["HTTP_REMOTE_ADDR"])) {
                $renderer->setProp("env_remoteaddr", $_SERVER["REMOTE_ADDR"]);
            }

            $macro = $this->_setDefaultMacro($macro);

            if (is_array($macro)) {
                foreach ($macro as $key => $value) {
                    $renderer->setProp($key, $value);
                }
            }
            if (isset($this->def[$template])) {
                $template = $this->def[$template];
            }
            
            $is_mobile_mail;
            if (is_array($to) && count($to) > 0) {
                $is_mobile_mail = Mobile_Util::isMobileMailAddress($to[0]);
            } else {
                $is_mobile_mail = Mobile_Util::isMobileMailAddress($to);
            }
            
            $this->mail_dir = $this->backend->ctl->getMaildir($is_mobile_mail);
            
            $mail = $renderer->perform(sprintf('%s/%s', $this->mail_dir, $template), true);
        }
        if ($to === null) {
            return $mail;
        }

        $mail = str_replace("\r\n", "\n", $mail);
        list($header, $body) = $this->_parse($mail);

        if ($attach !== null) {
            $attach = isset($attach[0]) ? $attach : array($attach);
            $boundary = Ethna_Util::getRandom(); 
            $body = "This is a multi-part message in MIME format.\n\n" .
                "--$boundary\n" .
                "Content-Type: text/plain; charset=iso-2022-jp\n" .
                "Content-Transfer-Encoding: 7bit\n\n" .
                "$body\n";
            foreach ($attach as $part) {
                if (isset($part['content']) === false
                    && isset($part['filename']) && is_readable($part['filename'])) {
                    $part['content'] = file_get_contents($part['filename']);
                    $part['filename'] = basename($part['filename']);
                }
                if (isset($part['content']) === false) {
                    continue;
                }
                if (isset($part['content-type']) === false) {
                    $part['content-type'] = 'application/octet-stream';
                }
                if (isset($part['name']) === false) {
                    $part['name'] = $part['filename'];
                }
                if (isset($part['filename']) === false) {
                    $part['filename'] = $part['name'];
                }
                $part['name'] = preg_replace('/([^\x00-\x7f]+)/e',
                    "Ethna_Util::encode_MIME('$1')", $part['name']); // XXX: rfc2231
                $part['filename'] = preg_replace('/([^\x00-\x7f]+)/e',
                    "Ethna_Util::encode_MIME('$1')", $part['filename']);

                $body .=
                    "--$boundary\n" .
                    "Content-Type: " . $part['content-type'] . ";\n" .
                        "\tname=\"" . $part['name'] . "\"\n" .
                    "Content-Transfer-Encoding: base64\n" . 
                    "Content-Disposition: attachment;\n" .
                        "\tfilename=\"" . $part['filename'] . "\"\n\n";
                $body .= chunk_split(base64_encode($part['content']));
            }
            $body .= "--$boundary--";
        }

        if (isset($header['mime-version']) === false) {
            $header['mime-version'] = array('Mime-Version', '1.0');
        }
        if (isset($header['subject']) === false) {
            $header['subject'] = array('Subject', 'no subject in original');
        }
        if (isset($header['content-type']) === false) {
            $header['content-type'] = array(
                'Content-Type',
                $attach === null ? 'text/plain;charset=ISO-2022-JP'
                                 : "multipart/mixed; \n\tboundary=\"$boundary\"",
            );
        }
        if (isset($header['content-transfer-encoding']) === false) {
            $header['content-transfer-encoding'] = array('Content-Transfer-Encoding', '7bit');
        }

        $header_line = "";
        foreach ($header as $key => $value) {
            if ($key == 'subject') {
                continue;
            }
            if ($header_line != "") {
                $header_line .= "\n";
            }
            $header_line .= $value[0] . ": " . $value[1];
        }

        if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
            $body = str_replace("\n", "\r\n", $body);
        }
        $header_line = str_replace("\n", "\r\n", $header_line);
        
        if ($this->config->get('debug')) {
            $mail_text  = PHP_EOL;
            $mail_text .= "------------------------------------------" . PHP_EOL;
            $mail_text .= $header_line . PHP_EOL;
            $mail_text .= "------------------------------------------" . PHP_EOL;
            $mail_text .= $body . PHP_EOL;
            $mail_text .= "------------------------------------------" . PHP_EOL;
            
            $this->backend->log(LOG_DEBUG, $mail_text);
        }
        
        foreach (to_array($to) as $rcpt) {
            if (!empty($this->option)) {
                mail($rcpt, $header['subject'][1], $body, $header_line, $this->option);
            } else {
                $mail_envelope_from = $this->config->get('mail_envelope_from');
                mail($rcpt, $header['subject'][1], $body, $header_line,"-f".$mail_envelope_from);
            }
            if ($this->config->get('debug')) {
                $this->backend->log(LOG_DEBUG, "send_to: " . $rcpt . PHP_EOL);
            }
        }
    }

    /**
     *
     *  @access protected
     *  @param  array
     *  @return array
     */
    function _setDefaultMacro($macro)
    {
        $default_macro = array(
            'site_name' => $this->config->get('site_name_short'),
            'site_url'  => $this->config->get('url'),
            'mail_from' => $this->config->get('mail_from'),
        );
        
        $macro = array_merge($default_macro, $macro);
        
        return $macro;
    }

    /**
     *
     *  @access private
     *  @param  string
     *  @return array
     */
    function _parse($mail)
    {
        list($header_line, $body) = preg_split('/\r?\n\r?\n/', $mail, 2);
        $header_line .= "\n";

        $header_lines = explode("\n", $header_line);
        $header = array();
        foreach ($header_lines as $h) {
            if (strstr($h, ':') == false) {
                continue;
            }
            list($key, $value) = preg_split('/\s*:\s*/', $h, 2);
            $i = strtolower($key);
            $header[$i] = array();
            $header[$i][] = $key;
            $header[$i][] = preg_replace('/([^\x00-\x7f]+)/e', "Ethna_Util::encode_MIME('$1')", $value);
        }

        $body = mb_convert_encoding($body, "ISO-2022-JP");

        return array($header, $body);
    }
}
// }}}
?>
